﻿using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Scripting;
using Microsoft.Scripting.Ast;
using Microsoft.Linq.Expressions;

namespace DlrBasic.Parser.Ast
{
    class Assign : Statement
    {
        DlrBasicExpression[] leftSide;
        DlrBasicExpression rightSide;

        public Assign(SourceSpan span, DlrBasicExpression[] leftSide, DlrBasicExpression rightSide)
            : base(span)
        {
            this.leftSide = leftSide;
            this.rightSide = rightSide;
        }

        protected internal override Expression Generate(DlrBasicGenerator generator, StateMemberGenerator stateParameter, LambdaBuilder builder)
        {
            if (leftSide.Length == 1)
            {
                Expression assign = leftSide[0].GenerateAssign(generator,
                    rightSide.Generate(generator));
                return Expression.Block(
                    assign, base.Generate(generator, stateParameter, builder));
            }
            else
            {
                Expression calculation = rightSide.Generate(generator);
                ParameterExpression tempVariable = builder.HiddenVariable(calculation.Type, "result");

                List<Expression> assignExpressions = new List<Expression>();
                assignExpressions.Add(Expression.Assign(tempVariable, calculation));

                for (int i = 0; i < leftSide.Length; i++)
                {
                    assignExpressions.Add(
                        leftSide[i].GenerateAssign(generator, tempVariable));
                }

                assignExpressions.Add(base.Generate(generator, stateParameter, builder));
                return Utils.Block(SourceSpan, assignExpressions.ToArray());
            }
        }
    }
}
